import React , { Component } from 'react';

class View extends Component {
    constructor(props){
        super(props);
        this.state = {
            allin:false,
            checkNode:[
                {name:'Vue',checked:false},
                {name:'React',checked:false},
                {name:'Angular',checked:false},
                {name:'Ember',checked:false}
            ]
        }
    }
    handleChange(e){
        let name = e.target.name;
        let checked = e.target.checked;
        // 全选 反选
        if(checked){
            // for(let i in checkNode){
            //     console.log(checkNode[i])
            // }
            this.state.checkNode.forEach(v=>{
                v.checked = true;
            })
        }else {
            this.state.checkNode.forEach(v=>{
                v.checked = false;
            })
        }

        this.setState({
            [name]:checked,
            checkNode:this.state.checkNode
        })
    }
    _handleChange(e,key){
        const checkNode = this.state.checkNode;
        checkNode[key].checked = !checkNode[key].checked;
        let bTure = true;
        for(let i=0,len=this.state.checkNode.length;i<len;i++){
            if(!this.state.checkNode[i].checked){
                bTure = false;
                break;
            }
        }
        this.setState({
            allin:bTure,
            checkNode:checkNode
        })
    }
    render(){
        console.log(this.state.checkNode)
        const checkList = this.state.checkNode.map((val,key)=>{
            return (
                <li key={key}>
                    <input id={`lb`+key} type="checkbox" checked={val.checked}
                    onChange={(e)=>this._handleChange(e,key)}/>
                    <label htmlFor={`lb`+key}>{val.name}{val.checked}</label>
                </li>

            )

        })
        return(
            <div>
                <h2>这是一个全选的demo</h2>
                <h3>
                    <input type="checkbox"
                    name="allin"
                    checked={this.state.allin}
                    onChange={(e)=>this.handleChange(e)}
                    />
                </h3>
                <ul>
                    {checkList}
                </ul>
            </div>
        )
    }
}
export default View;
